package com.goroom.base58;

import javax.xml.bind.DatatypeConverter;

/**
 * Created by fengbaolong on 2017/12/20.
 */
public class Base58 {
    public static final char[] ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".toCharArray();
    private static final char ENCODED_ZERO = ALPHABET[0];

    public Base58() {

    }

    /**
     * return string encode using base58
     * @param str word
     * @return encoded word
     */
    public String encode(String str) {

        // getByte
        byte [] b = str.getBytes();

        // string → Hex
        String s_hex = DatatypeConverter.printHexBinary(b);

        // Hex → Decimal
        long decimal = Long.valueOf(s_hex, 16);

        // Decimal → 58 kinds of characters
        StringBuffer res = new StringBuffer();
        while (decimal > 0) {
            char c = ALPHABET[(int)decimal%58];
            res.append(c);
            decimal = decimal/58;
        }

        // zero byte confirm
        byte [] temp_b = str.getBytes();
        for (int i = 0; i < temp_b.length; i++) {
            if (temp_b[i] != 0) {
                break;
            }
            res.append(ENCODED_ZERO);
        }

        return res.reverse().toString();
    }

    /**
     * return original string
     * @param encoded word
     * @return original word
     */
    public String decode(String str) {

        int decimal = 0;

        // restore decimal.
        char []chars = str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char temp_c = chars[i];

            int index_num = 0;
            for (int j = 0; j < ALPHABET.length; j++) {
                if (ALPHABET[j] == temp_c) {
                    index_num = j;
                }
            }

            decimal = decimal*58;
            decimal = decimal + index_num;
        }

        // Decimal → Hex
        String s_hex = Integer.toHexString((int)decimal);

        // Hex → string
        byte[] bytes = DatatypeConverter.parseHexBinary(s_hex);
        return new String(bytes);
    }

    public static void main(String[] args) {
        System.out.println(ALPHABET.length);
    }
}
